<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      handler(val) {
        if (val.length > 0) {
          this.$nextTick(() => {
            this.initChart()
          })
        }
      },
      deep: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        color: ['#0046A4', '#0071D2', '#1190FF', '#00BFFB', '#4DD2FC', '#2BFFF2', '#6DFF9F', '#F0FF43'],
        tooltip: {
          trigger: 'item',
          triggerOn: 'mousemove',
          formatter: function(p) {
              return p.data.keyName
          }
        },
        series: [
          {
            type: 'tree',
            data: this.chartData,
            top: '1%',
            left: '7%',
            bottom: '1%',
            right: '20%',
            symbolSize: 7,
            initialTreeDepth: '4',
            label: {
              position: 'left',
              verticalAlign: 'middle',
              align: 'right',
              fontSize: 9,
              formatter: function(p) {
                  if (p.data.status === 'N') {
                    return '{noPass|' + p.data.keyName + '}'
                  } else {
                    return '{pass|' + p.data.keyName + '}'
                  }
                  // return p.data.keyName
              },
              rich: {
                pass: {
                  color: 'green'
                },
                noPass: {
                  color: 'red'
                }
              }
            },
            leaves: {
              label: {
                position: 'right',
                verticalAlign: 'middle',
                align: 'left'
              }
            },
            emphasis: {
              focus: 'descendant'
            },
            expandAndCollapse: true,
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      })
    }
  }
}
</script>
